package com.moive.news.tqnewsapplication.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.moive.news.tqnewsapplication.R;
import com.moive.news.tqnewsapplication.base.Adapter.BaseListAdapter;
import com.moive.news.tqnewsapplication.base.BaseActivity;
import com.moive.news.tqnewsapplication.entity.NewsPinlunInfo;
import com.moive.news.tqnewsapplication.entity.ResourcesManager;
import com.moive.news.tqnewsapplication.networks.BaseApi;
import com.moive.news.tqnewsapplication.okmanager.OkManagerCallback;
import com.moive.news.tqnewsapplication.utils.GetSystemTimeUitl;
import com.moive.news.tqnewsapplication.utils.LogUtil;
import com.moive.news.tqnewsapplication.utils.PreferenceUtil;
import com.moive.news.tqnewsapplication.utils.TimeUtil;
import com.moive.news.tqnewsapplication.utils.ToastUtils;
import com.moive.news.tqnewsapplication.weight.MakeListView;
import com.moive.news.tqnewsapplication.weight.mylistview.SecondXListView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import onekeyshare.OnekeyShare;

/**
 * Created by Administrator on 2017/12/8.
 * 新闻详情
 */
public class NewsDteilsAcitivity extends BaseActivity implements  SecondXListView.IXListViewListener {
    @BindView(R.id.news_back)
    ImageView newsBack;
    @BindView(R.id.newsdetils_title)
    TextView newsdetilsTitle;
    @BindView(R.id.collect_text)
    TextView collectText;
    @BindView(R.id.news_share)
    ImageView newsShare;
    @BindView(R.id.news_dianzan)
    ImageView newsDianzan;
    @BindView(R.id.chatContent)
    EditText chatContent;
    @BindView(R.id.voiceLayout)
    ImageView voiceLayout;
    @BindView(R.id.chatSendBtn)
    TextView chatSendBtn;
    @BindView(R.id.inputRelativeLayout)
    RelativeLayout inputRelativeLayout;
    @BindView(R.id.newsdetils_listview)
    SecondXListView newsdetilsListview;
    @BindView(R.id.news_comment)
    TextView newsComment;
    @BindView(R.id.news_dianzan_number)
    TextView newsDianzanNumber;
    private String collectid;
    private View view;
    private Gson gson = new Gson();
    private int page = 1;
    List<NewsPinlunInfo.DataBean> list = new ArrayList<>();
    NewsPinlunAdapter adapter;
    WebView newdetils_web;
    private String inputurl = "", token = "", comment = "";
    private int type = -1;
    DymicList02Adapter ad;
    private String id = "", parent_id = "",isCurrentUserLike="";
    private int like=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        ButterKnife.bind(this);
        getview();
    }
    private void getview() {
        Intent intent = getIntent();
        if (intent != null) {
            Bundle b = intent.getExtras();
            if (b != null) {
                token = PreferenceUtil.getString("token", "");
                collectid = b.getString("url", "www.baidu.com");
                comment = b.getString("comment", "");
                isCurrentUserLike=b.getString("isCurrentUserLike","");
                inputurl = BaseApi.NEWS_TYPE_ITEM_TYPE + collectid + "&token=" + token;
                LogUtil.i("li", inputurl);
            }
        }
        if (!TextUtils.isEmpty(isCurrentUserLike)&&isCurrentUserLike.equals("1")){
            newsDianzan.setBackgroundResource(R.drawable.icon_dianzan02);
        }else {
            newsDianzan.setBackgroundResource(R.drawable.icon_dianzan01);
        }
        view = LayoutInflater.from(NewsDteilsAcitivity.this).inflate(R.layout.activity_webview_head, null);
        newdetils_web = view.findViewById(R.id.newdetils_web);
        newdetils_web.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放
        newdetils_web.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        newdetils_web.getSettings().setBuiltInZoomControls(true);
        // 为图片添加放大缩小功能
        newdetils_web.getSettings().setUseWideViewPort(true);
        newdetils_web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                newdetils_web.loadUrl(url);
                return true;
            }
        });
        newdetils_web.loadUrl(inputurl);
        adapter = new NewsPinlunAdapter(NewsDteilsAcitivity.this);
        newsdetilsListview.setAdapter(adapter);
        newsdetilsListview.addHeaderView(view);
        newsdetilsListview.setPullRefreshEnable(false);
        getdata();

//  new Thread(){
//      @Override
//      public void run() {
//          super.run();
//          try {
//              Thread.sleep(1000);
//
//          } catch (InterruptedException e) {
//              e.printStackTrace();
//          }
//      }
//  }.start();
        getnumber();
    }
    private void collect() {
        if (TextUtils.isEmpty(PreferenceUtil.getString("token", ""))) {
            ToastUtils.ShortToast("你还未登录，请前往登录");
            return;
        }
        OkHttpUtils.post()
                .url(BaseApi.COLLECT)
                .addParams("token", token)
                .addParams("newsId", collectid)
                .build().execute(new OkManagerCallback(this) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }
            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        ToastUtils.ShortToast("收藏成功");
                        collectText.setText("已收藏");
                    } else {
                        ToastUtils.ShortToast(jsonObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick({R.id.news_back, R.id.news_share, R.id.news_dianzan, R.id.collect_text, R.id.chatSendBtn, R.id.news_comment})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.news_back:
                finish();
                break;
            case R.id.news_share:
                onOneKeyShare();
                break;
            case R.id.news_dianzan:
                dianzan();
                break;
            case R.id.collect_text:
                collect();
                break;
            case R.id.chatSendBtn:
                if (TextUtils.isEmpty(PreferenceUtil.getString("token",""))){
                    ToastUtils.ShortToast("你还未登录，无法评论！");
                    return;
                }
                //发表父评论
                if (type == 0) {
                    comment(chatContent.getText().toString(), collectid, "", "");
                } else {
                    //发表子评论
                    if (!TextUtils.isEmpty(id)) {
                        comment(chatContent.getText().toString(), "", parent_id, id);
                    }
                }
                break;
            case R.id.news_comment:
                if (inputRelativeLayout.getVisibility() == View.GONE) {
                    inputRelativeLayout.setVisibility(View.VISIBLE);
                    type = 0;
                }
                break;
        }
    }
    //评论接口commit 评价内容 emotionID动态id ，parentCommentID父评论id,toUserId 发给某人id
    private void comment(String commit, String emotionID, String parentCommentID, String toUserId) {
        String token = PreferenceUtil.getString("token", "");
        OkHttpUtils.post()
                .url(BaseApi.NEWS_COMMENT)
                .addParams("token", token)
                .addParams("newsId", emotionID)
                .addParams("content", commit)
                .addParams("parentId", parentCommentID)
                .addParams("toUserId", toUserId)
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }
            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        ToastUtils.ShortToast("评论成功！");
                        list.clear();
                        getdata();
                        if (inputRelativeLayout.getVisibility() == View.VISIBLE) {
                            inputRelativeLayout.setVisibility(View.GONE);
                            chatContent.setText("");
                            type = 0;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //获取所有新闻评论
    private void getdata() {
        OkHttpUtils.get()
                .url(BaseApi.NEWS_LOOK_COMMENT)
                .addParams("newsId", collectid)
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") == 0) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        if (jsonArray != null) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject1 = (JSONObject) jsonArray.get(i);
                                NewsPinlunInfo.DataBean dataBean1 = gson.fromJson(jsonObject1 + "", NewsPinlunInfo.DataBean.class);
                                list.add(dataBean1);
                            }
                            adapter.addItems(list);

                            if (type == 1) {
                                adapter.notifyDataSetChanged();
                                type = -1;
                            } else if (type == 0) {
                                adapter.notifyDataSetChanged();
                                type = -1;
                            }
                        }
                        if (jsonArray.length() == 0) {
//                            ToastUtils.ShortToast("没有更多数据了！");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onRefresh() {
        page = 1;
        list.clear();
        getdata();
        adapter.notifyDataSetChanged();
        stopOnLoad();
    }
    private void stopOnLoad() {
        newsdetilsListview.stopRefresh();
        newsdetilsListview.stopLoadMore();
        newsdetilsListview.setRefreshTime(GetSystemTimeUitl.getTime());
    }
    @Override
    public void onLoadMore() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;

                getdata();
                adapter.notifyDataSetChanged();
                stopOnLoad();
            }
        }, 1000);
    }

    public class NewsPinlunAdapter extends BaseListAdapter<NewsPinlunInfo.DataBean> {
        private Context context;

        public NewsPinlunAdapter(Context context) {
            this.context = context;
        }

        @Override
        protected View getItemView(int position, View convertView, ViewGroup parent, List<NewsPinlunInfo.DataBean> item) {
            ViewHolder viewHolder = null;
            if (viewHolder == null) {
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.newspinlun_item, null);
                viewHolder.newspinglun_img = convertView.findViewById(R.id.newspinglun_img);
                viewHolder.newspinglun_nichen = convertView.findViewById(R.id.newspinglun_nichen);
                viewHolder.newspinglun_time = convertView.findViewById(R.id.newspinglun_time);
                viewHolder.newspinglun_desrc = convertView.findViewById(R.id.newspinglun_desrc);
                viewHolder.newsdteils_number = convertView.findViewById(R.id.newsdteils_number);
                viewHolder.newsdetils_dianzan_img = convertView.findViewById(R.id.newsdetils_dianzan_img);
                viewHolder.makelistview = convertView.findViewById(R.id.makelistview);
                convertView.setTag(this);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            Glide.with(context)
                    .load(item.get(position).getFromUserHeadImg())
                    .centerCrop()
                    .dontAnimate()
                    .placeholder(R.drawable.icon)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(viewHolder.newspinglun_img);
            viewHolder.newspinglun_nichen.setText(item.get(position).getFromUserNickName());
            String time = TimeUtil.parseDateTime(item.get(position).getCreateDate());
            viewHolder.newspinglun_time.setText(time);
            String comment = "";
            try {
                comment = URLDecoder.decode(item.get(position).getContent(), "UTF-8");
                viewHolder.newspinglun_desrc.setText(comment);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//            ad = new DymicList02Adapter(context, list.get(position).getChildrenComments(), list.get(position).getId());
//            viewHolder.makelistview.setAdapter(ad);

            return convertView;
        }

        class ViewHolder {
            private CircleImageView newspinglun_img;
            private TextView newspinglun_nichen;
            private TextView newspinglun_time;
            private TextView newspinglun_desrc;
            private TextView newsdteils_number;
            private ImageView newsdetils_dianzan_img;
            private MakeListView makelistview;
        }
    }

    public class DymicList02Adapter extends BaseAdapter {
        private Context context;
        private List<NewsPinlunInfo.DataBean.ChildrenCommentsBean> childrenCommentsBeanList;
        private String page;

        public DymicList02Adapter(Context context, List<NewsPinlunInfo.DataBean.ChildrenCommentsBean> childrenCommentsBeanList, String page) {
            this.context = context;
            this.childrenCommentsBeanList = childrenCommentsBeanList;
            this.page = page;
        }

        @Override
        public int getCount() {
            return childrenCommentsBeanList.size();
        }

        @Override
        public Object getItem(int position) {
            return childrenCommentsBeanList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHodler02 viewHodler02 = null;
            if (viewHodler02 == null) {
                viewHodler02 = new ViewHodler02();
                convertView = LayoutInflater.from(context).inflate(R.layout.expandablelistview_two, null);
                viewHodler02.fromuser02_name = convertView.findViewById(R.id.fromuser02_name);
//                viewHodler02.fromUser02_comment = convertView.findViewById(R.id.fromUser02_comment);
//                viewHodler02.touser_name = convertView.findViewById(R.id.touser_name);
                convertView.setTag(viewHodler02);
            } else {
                viewHodler02 = (ViewHodler02) convertView.getTag();
            }
            viewHodler02.fromuser02_name.setText(childrenCommentsBeanList.get(position).getFromUserNickName());
            try {
                String comment = URLDecoder.decode(childrenCommentsBeanList.get(position).getContent(), "UTF-8");
                viewHodler02.fromUser02_comment.setText(comment);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }


            viewHodler02.touser_name.setText(childrenCommentsBeanList.get(position).getToUserNickName());
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (inputRelativeLayout.getVisibility() == View.GONE) {
                        inputRelativeLayout.setVisibility(View.VISIBLE);
                        type = 1;
                        id = childrenCommentsBeanList.get(position).getFromUserId();
                        parent_id = page;
                    }
                }
            });
            return convertView;
        }

        class ViewHodler02 {
            private TextView fromuser02_name;
            private TextView touser_name;
            private TextView fromUser02_comment;
        }
    }

    //分享
    private void onOneKeyShare() {
        OnekeyShare oks = new OnekeyShare();
        oks.setText(comment);
        oks.setTitle("爱小道分享");
        oks.setTitleUrl("www.tqiant.com");
        oks.setImageUrl(inputurl);
        oks.setSilent(true);
        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + " completed at " + msg;
                ToastUtils.ShortToast("分享成功！");
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + "caught error at " + msg;
                ToastUtils.ShortToast("分享失败！");
            }

            @Override
            public void onCancel(Platform platform, int i) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + " canceled at " + msg;
//                ToastUtils.ShortToast(text);
            }
        });
        Bitmap logo = BitmapFactory.decodeResource(NewsDteilsAcitivity.this.getResources(), R.mipmap.ic_launcher);
        String label = NewsDteilsAcitivity.this.getString(R.string.app_name);
        View.OnClickListener listener = new View.OnClickListener() {
            public void onClick(View v) {
                String text = "Customer Logo -- ShareSDK " + ShareSDK.getSDKVersionName();
                Toast.makeText(NewsDteilsAcitivity.this, text, Toast.LENGTH_SHORT).show();
            }
        };
        oks.setCustomerLogo(logo, label, listener);
        oks.show(NewsDteilsAcitivity.this);
    }

    //点赞
    private void dianzan() {
        if (TextUtils.isEmpty(PreferenceUtil.getString("token", ""))) {
            ToastUtils.ShortToast("你还未登录，请前往登录");
            return;
        }
        OkHttpUtils.get()
                .url(BaseApi.NEWS_DIANZAN)
                .addParams("token", PreferenceUtil.getString("token", ""))
                .addParams("newsId", collectid)
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") == 0) {
                          int likes = like + 1;
                        newsDianzanNumber.setText(likes + "");
                        newsDianzan.setBackgroundResource(R.drawable.icon_dianzan02);
                    } else {
                        newsDianzan.setBackgroundResource(R.drawable.icon_dianzan02);
                        ToastUtils.ShortToast("你已经点过赞了");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getnumber() {
        OkHttpUtils.get()
                .url(BaseApi.NEWS_NUMBER)
                .addParams("newsId", collectid)
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("code") == 0) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                      like = jsonObject1.getInt("likeCount");
                        int commentCount = jsonObject1.getInt("commentCount");
                        newsDianzanNumber.setText("("+like+")");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
